# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django.template import Node, NodeList, Template, Context, resolve_variable
from django.template import get_library, Library, InvalidTemplateLibrary, TemplateSyntaxError
from django.template.loader import get_template
from django.db.models import get_model

register = Library()

class NavigationNode(Node):
    def __init__(self, template_path, wraptag, depth, follow):
        self.__default_structure = "core.Section"
        self.__model = get_model(*self.__default_structure.split('.'))
        self.__template = get_template(template_path)
        self.__wraptags = ('<%s class="section">' % wraptag, '</%s>' % wraptag)
        self.__depth = depth
        self.__follow = follow
         
    def render(self, context):
        nodes = NodeList()
        if self.__follow:
            root = self.__model.objects.filter(parent__isnull=True)[0]
            current_section = self.__model.objects.get(pk=context["section"].id)
            try:
                back = self.__model.objects.get(pk=current_section.parent_id)
                back.name = "Torna indietro"
            except:
                back = None
            related_content = []
            if current_section != root:
                related_content = [root,]
                if back != root and back != None:
                    related_content.append(back)
            related_content.extend(list(self.__model.objects.getRelatedSection(context["user"], current_section)))
        else:
            related_content = self.__model.objects.getSections(context["user"])

        related_content.sort(lambda x,y:cmp(x.order,y.order))
        
        def _get_childs(parent):
            nodes.append(self.__wraptags[0])
            if parent.parent == parent:
                for node in self.__template:
                    nodes.append(node.render(context))
            
            #for child in parent.subsections.order_by('-order'):
            for child in self.__model.objects.getRelatedSection(context["user"], parent):
                context['menu'] = child
                for node in self.__template:
                    nodes.append(node.render(context))
                _get_childs(child)
            nodes.append(self.__wraptags[1])
            return 

        for content in related_content:
            if not content.parent or self.__follow:
                #context['menu'] = content
                if content.viewtype == "core:Redirect":
                    context['menu'] = {"slug":content.description, "name":content.name}
                else:
                    context['menu'] = {"slug":"/"+content.slug+"/", "name":content.name}

                for node in self.__template:
                    nodes.append(node.render(context))
                
                if self.__depth == -1 or self.__depth > 1:
                    _get_childs(content)
                    if self.__depth > 1:
                        self.__depth -= 1 
                
        return nodes.render(context)
    
def get_menu(parser, token):
    """
        example tags:
        {% get_menu from "this_section" using "template_name" wrapped_by "ul" depth 2 %}
        {% get_menu from "Blog" wrapped_by "div" %}
    """
    # estrazione parametri
    params = token.contents.split()

    # parametri di default
    follow = False
    depth = -1
    wraptag = "ul"
    default_wrappers = ["ul", "ol", "div", "p"]
    
    if "follow" in params:
        follow = bool(params[params.index('follow')+1][1:-1])
    
    if "depth" in params:
        depth = int(params[params.index('depth')+1][1:-1])
                
    if "using" in params:
        template = "%s.html" % params[params.index("using")+1][1:-1]
    
    if "wrapped_by" in params:
        if params[params.index("wrapped_by")+1][1:-1] in default_wrappers:
            wraptag = params[params.index("wrapped_by")+1][1:-1]
    
    return NavigationNode(template, wraptag, depth, follow)
get_menu = register.tag(get_menu)
